package com.skeyedu.filter;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @Description 监听器
 * @Author 羽落陌殇
 * @Date 2021/7/15 17:44
 * @Version 1.0.0
 */
public class OnlineCountListener implements HttpSessionListener {
    private Integer onlineCount = 0;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("创建监听");
        // 创建Session监听
        System.out.println(se.getSession().getId());
        ServletContext context = se.getSession().getServletContext();
        onlineCount = (Integer) context.getAttribute("OnlineCount");
        if (onlineCount == null) {
            onlineCount = new Integer(1);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count + 1);
        }
        context.setAttribute("OnlineCount", onlineCount);
    }

    // 销毁Session监听
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("销毁监听");
        ServletContext ctx = se.getSession().getServletContext();
        onlineCount = (Integer) ctx.getAttribute("OnlineCount");
        if (onlineCount == null) {
            onlineCount = new Integer(0);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count - 1);
        }
        ctx.setAttribute("OnlineCount", onlineCount);
    }
}
